package com.wgu.modules.service.impl;

import com.wgu.common.utils.Assert;
import com.wgu.entity.UserInfo;
import com.wgu.modules.dto.UserDTO;
import com.wgu.modules.repository.UserRepository;
import com.wgu.modules.service.UserService;
import com.wgu.modules.web.vo.UserVO;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: w
 * @Date: 2019/6/24 15:36
 * @Version 1.0
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(UserVO userVO) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(userVO.getUsername());
        userInfo.setRealName(userVO.getRealName());
        userRepository.save(userInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Assert.isTrue(userRepository.existsById(id),"此id不存在");
        userRepository.deleteById(id);
    }

    @Override
    public List<UserDTO> list(Pageable pageable) {
        List<UserInfo> list = userRepository.findAll();
        List<UserDTO> dtoList = new ArrayList<>();
        list.forEach(userInfo -> {
            UserDTO userDTO = new UserDTO();
            userDTO.setId(userInfo.getId());
            userDTO.setUsername(userInfo.getUsername());
            userDTO.setRealName(userInfo.getRealName());
            dtoList.add(userDTO);
        });
        return dtoList;
    }
}
